package com.itita.ww2.handler.requesthandler.lottery;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.game.lottery.LotteryService;
import com.itita.ww2.game.user.UserInventoryManager;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.handler.IRequestOper;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;

public class LotteryByTimes implements IRequestOper {

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		UserProfile userProfile = UserService.getInstance().getUserProfile(user);
		int times = params.getInt("times");

		List<Integer> items = new ArrayList<>();
		UserInventoryManager inventory = userProfile.getInventory();
		inventory.backup();
		try {
			items = LotteryService.lottery(userProfile, times);
		} catch (Exception e) {
			inventory.rollback();
			throw e;
		} finally {
			inventory.clean();
		}

		inventory.update();
		inventory.sync();

		ISFSObject backObj = SFSObject.newInstance();
		backObj.putIntArray("result", items);
		MessageHandler.getInstance().sendMsg(requestCMD, backObj, user, null, true);
		return true;
	}

}
